import axios from "axios"
import { message } from "antd"

const baseURL = "http://localhost:3000" // 基路径

const AUTH_TOKEN = ""

axios.defaults.baseURL = baseURL;

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"


export function ShowLoading(msg?: string) {
    msg = msg || '加载中'
    message.destroy()
    message.loading(msg)
}

export function ShowSuccess(msg?: string) {
    msg = msg || '请求成功'
    message.destroy()
    message.success(msg)
}

export function ShowError(msg?: string) {
    msg = msg || '请求失败'
    message.destroy()
    message.error(msg)
}


// 拦截器 Interceptors
// 请求发送的拦截器 request
axios.interceptors.request.use(function (config: any) {
    // 成功
    // loading
    var token = sessionStorage.getItem("token") ? sessionStorage.getItem("token") : ''
    config.headers.token = token //请求头
    ShowLoading()
    return config
}, function (error) {
    ShowError("请求发送失败")
    return Promise.reject(error)
})

// 请求响应的拦截器 response
axios.interceptors.response.use(function (response) {
    // 成功
    console.log(response.data)
    // PC端需要对应的提示
    if (response.data.code == 200) {
        ShowSuccess(response.data.msg)
    } else {
        if (response.data.code == 3300) {
            // token失效，重新登录
        }
        ShowError(response.data.msg)
    }
    return response
}, function (error) {
    // console.log(error)
    ShowError("响应失败")
    return Promise.reject(error)
})


// axios 二次封装
export function get(url: any, params: any, headers: any) {
    return new Promise(function (resolve, reject) {
        axios.get(url, {
            params,
            headers
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function post(url: any, body: any, headers: any) {
    return new Promise(function (resolve, reject) {
        axios.post(url, body, {
            headers
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function patch(url: any, params: any, headers: any) {
    return new Promise(function (resolve, reject) {
        axios({
            url,
            method: "patch",
            data: params,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function Delete(url: any, params: any, headers: any) {
    return new Promise(function (resolve, reject) {
        axios({
            url,
            method: "delete",
            data: params
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}


export {
    axios,
    baseURL
}